package com.open.free.generator.utils;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.open.free.generator.entity.Source;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;

/**
 * @author Faye.Wang
 * @version 1.0
 * @date 2020/12/29 23:29
 * @Description
 */
public class DataSourceFactory {

    private static final Logger logger = LoggerFactory.getLogger(DataSourceFactory.class);

    private static SqlSessionFactory getSqlSessionFactory(Source source){
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl(source.getDbSourceUrl());
        dataSource.setUsername(source.getDbUserName());
        dataSource.setPassword(source.getDbPassWord());
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        try {
            return sqlSessionFactoryBean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("----------------数据库创建连接失败------------------------");
            return null;
        }
    }

    public static Connection getConnection(Source source){
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(source);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession.getConnection();
    }

}
